import threading
from common import utils
import socket
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from ui.Ui_main_window import Ui_MainWindow

class MainWindow(QMainWindow):

    #a.定义信号（需要一个str参数）
    msg_signal = pyqtSignal(str)

    
    def __init__(self):
        super().__init__()  
        
        self.ui = Ui_MainWindow()
        #加载ui对象
        self.ui.setupUi(self)
        #tcp客户端socket对象
        self.tcp_client:socket.socket = None

        #c.信号连接到槽函数
        self.msg_signal.connect(self.on_msg_signal_emit)
        
        self.init_ui()
        
    
        
    def update_connect_state(self):
        if self.tcp_client == None:
            #连接网络
            self.ui.btn_connect.setText("连接网络")
        else:
            self.ui.btn_connect.setText("断开连接")
            
    # b.定义槽函数
    @pyqtSlot(str)
    def on_msg_signal_emit(self,msg):
        thread_name = threading.current_thread().name
        print(msg,"thread->",thread_name)
    
    
    def run_tcp_client(self,target_ip,target_port):
        
        #创建socket对象并连接服务器
        self.tcp_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        #连接服务器
        try:
            self.tcp_client.connect((target_ip,int(target_port)))   #ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝，无法连接。
            
        except Exception as e:
            print("连接服务器失败，请重试！")
            self.tcp_client = None
            return 
        
        self.update_connect_state()
        
        local_ip,local_port = self.tcp_client.getsockname()
        print(f"服务器连接成功,本机信息ip:{local_ip} port:{local_port}")
        try:
            while True:
                #阻塞接收消息
                bytes_data = self.tcp_client.recv(1024)
                if bytes_data:
                    msg = utils.decode_data(bytes_data) 
                    print("收到数据:",msg)
                    
                    #子线程不能直接操作主线程UI组件，会出现争抢问题
                    self.ui.plainTextEdit.appendPlainText(msg)
                else:
                    print("断开服务器!")
                    break
        except:

            print("已断开连接！")
            
        if self.tcp_client is not None:    
            self.tcp_client.close()
            self.tcp_client = None
            
        self.update_connect_state()          
                
    
    @pyqtSlot()
    def on_btn_connect_clicked(self):
        """连接服务器
        1.获取用户输入的ip和端口号
        2.先创建子线程
        3.创建socket对象并连接服务器
        4.循环数据接受
        """
        if self.tcp_client != None:
            
            self.tcp_client.close()
            self.tcp_client = None
            return
        
        
        #1.获取用户输入的ip和端口号
        mode = self.ui.cb_mode.currentText()
        target_ip = self.ui.lineEdit_2.text()
        target_port = self.ui.lineEdit_3.text()
        print(f"mode:{mode},ip:{target_ip},port:{target_port}")
        
        #2.创建子线程,运行接收socket任务
        t1 = threading.Thread(target=self.run_tcp_client,args=(target_ip,target_port),daemon=True)
        t1.start()
        
        
    @pyqtSlot()
    def on_btn_send_clicked(self):
        text = self.ui.plainTextEdit_2.toPlainText()
        
        if len(text) == 0:
            self.statusBar().showMessage("请输入内容",1000)
            return
        
        if self.tcp_client is None:
            self.statusBar().showMessage("请先连接服务器，再发送！",1000)
            QMessageBox.warning(self,"发送失败","请先连接服务器,再发送数据!")
            return
            
        self.tcp_client.send(text.encode())

    def init_ui(self):
        self.ui.lineEdit_2.setText("127.0.0.1")
        self.ui.lineEdit_3.setText("8080")
        

if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MainWindow()
    widget.show()
    sys.exit(app.exec_())
